package com.ruoyi.rva.service.impl;

import com.github.pagehelper.PageHelper;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.PageDomain;
import com.ruoyi.common.core.page.TableSupport;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.sql.SqlUtil;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.rva.service.IRvaSystemService;
import com.ruoyi.rva.util.RvaJsonUtils;
import com.ruoyi.rva.util.RvaUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Slf4j
@Transactional
@Service
public class RvaSystemServiceImpl implements IRvaSystemService {

    @Autowired
    private TokenService tokenService;

    @Override
    public SysUser getLoginUser() {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        if (loginUser == null) {
            throw new CustomException("用户未登录！");
        }
        return loginUser.getUser();
    }

    @Override
    public void startPage() {
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();
        if (StringUtils.isNotNull(pageNum) && StringUtils.isNotNull(pageSize))
        {
            // String orderBy = SqlUtil.escapeOrderBySql(pageDomain.getOrderBy());
            PageHelper.startPage(pageNum, pageSize);
        }
    }

    private final static String ORDER_BY_LIST = "orderByList";

    @Override
    public List<Map> getOrderBys() {
        String parameter = ServletUtils.getParameter(ORDER_BY_LIST);
        if (RvaUtils.isEmpty(parameter)) {
            return new ArrayList<>();
        }
        return RvaJsonUtils.readAsList(parameter, Map.class);
    }
}
